package com.xy.smartplatfrom.controller;

import com.xy.smartplatfrom.dto.R;
import com.xy.smartplatfrom.events.UserLoginEvent;
import com.xy.smartplatfrom.pojo.User;
import com.xy.smartplatfrom.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * projectName:smartplatfrom
 * author:xiaoyang
 * time:2021/12/30 20:38
 * description:
 */
@RestController
@RequestMapping("/users")
public class UserController {

    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

  private UserService userService;

  @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/regist")
    public R regist(@RequestBody User user){
       userService.addUser(user);
       return R.setOK();
    }



    @PostMapping("/login")
     public R login(String username, String password,  HttpSession session){
        User user = userService.login(username, password);
         session.setAttribute("user",user);
//        System.out.println("111111111");
        context.publishEvent(new UserLoginEvent());
         return R.setOK(user.getUsername());
    }
}
